package cn.com.demo.java;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.CountDownLatch;

/**
 * CallHttpRequest
 * Created by wl on 2016/1/20.
 */
public class CallHttpRequest implements Runnable {

	public static int successRequest = 0;
	public static int failRequest = 0;
	public static int timeOutRequest = 0;
	private final String hostString = "http://localhost:";
	private String port;
	private String puductPartURL;

	private CountDownLatch begin;
	private CountDownLatch end;

	CallHttpRequest(String port, String puductPartURL, CountDownLatch begin, CountDownLatch end){
		this.port = port;
		this.puductPartURL = puductPartURL;
		this.begin = begin;
		this.end = end;
	}

	private String makeFullURL() {
		return hostString + port + puductPartURL;
	}

	private  static synchronized void incrementSuccessCount(){
		successRequest++;
	}

	private  static synchronized void incrementFailCount(){
		failRequest++;
	}

	private static synchronized void incrementTimeOutCount(){
		timeOutRequest++;
	}

	@Override
	public void run() {
		String urlStr = makeFullURL();
		URL url;
		try {
			begin.await();
			url = new URL(urlStr);
			URLConnection urlConnection = url.openConnection();
			HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
			httpURLConnection.setConnectTimeout(3000);
			int responseCode = httpURLConnection.getResponseCode();
			if(responseCode == HttpURLConnection.HTTP_OK){
				incrementSuccessCount();
			}
			else {
				incrementFailCount();
			}
		} catch (InterruptedException e) {
			incrementTimeOutCount();
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			end.countDown();
		}

	}
}
